/**
 * Created with IntelliJ IDEA.
 * Description:最大连续1的个数III
 * User: bjc
 * Date: 2025-11-10
 * Time: 15:34
 */
public class Test03_longestOnes {
    //没有优化
    public static int longestOnes(int[] nums, int k) {
        int left = 0,right = 0;
        int ret = 0;//表示最终结果
        int[] hash = new int[2];//关注下标为0上的元素值，下标为1元素值不参考
        int len = nums.length;
        while(right < len){
            //进窗口
            hash[nums[right]]++;
            while(hash[0] > k){
                //出窗口
                hash[nums[left]]--;
                left++;
            }
            //更新结果
            ret = Math.max(ret,right-left+1);
            right++;
        }
        return ret;
    }
    //优化代码：因为不关注1的个数，所以可以只记录0的个数
    public static int longestOnes1(int[] nums, int k) {
        int left = 0,right = 0;
        int ret = 0;
        int zero = 0;//用来记录0的个数
        while (right < nums.length){
            if(nums[right] == 0){
                zero++;
            }
            while(zero > k){
                if(nums[left] == 0) zero--;
                left++;
            }
            ret = Math.max(ret,right-left+1);
            right++;
        }
        return ret;
    }

    public static void main(String[] args) {
        int[] nums = {1,1,1,0,0,0,1,1,1,1,0};
        System.out.println(longestOnes1(nums,2));
    }
}
